/**
 * 
 */
package kr.pe.johnkim.dayve.activity;

import java.util.List;

import android.app.Activity;
import android.app.ActivityManager;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ActivityManager.RunningTaskInfo;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.content.SharedPreferences.OnSharedPreferenceChangeListener;
import android.os.Bundle;
import android.preference.Preference;
import android.preference.PreferenceActivity;

/**
 * @author johnkim
 *
 */
public class DayvePreferenceView extends PreferenceActivity implements OnSharedPreferenceChangeListener {

	private static final String TAG = DayvePreferenceView.class.getSimpleName();
	
	private static final String DAYVE_CONFIG = "dayve_config";
	
	private Preference mPreference;
	
	// 프로그램을 종료 한다.
	private static final int ALERT_DIALOG_EXIT_ID = 108;
	
	public static Activity activity;
	
	/* (non-Javadoc)
	 * @see android.preference.PreferenceActivity#onCreate(android.os.Bundle)
	 */
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		
		activity = this;
		
		addPreferencesFromResource(R.xml.preference);
		mPreference = (Preference)getPreferenceScreen().findPreference(DAYVE_CONFIG);
	}

	public void onSharedPreferenceChanged(SharedPreferences arg0, String arg1) {
		// TODO Auto-generated method stub
		
	}
	
	/**
	 * 뒤로 가기 버튼을 터치하면 프로그램 종료 여부를 확인 한다.
	 */
	@Override
	protected Dialog onCreateDialog(int id) {

		AlertDialog dlg;

		switch (id) {
		case ALERT_DIALOG_EXIT_ID:
			dlg = new AlertDialog.Builder(this).setIcon(R.drawable.icon)
			.setTitle(getResources().getString(R.string.preference_exit_program_title))
			.setMessage("\n" + getResources().getString(R.string.preference_exit_program_message) + "\n")
			.setNegativeButton(getResources().getString(R.string.preference_exit_program_button_cancel), 
					new DialogInterface.OnClickListener() {

				//                                @Override
				public void onClick(DialogInterface dialog, int which) {

				}
			}).setPositiveButton(getResources().getString(R.string.preference_exit_program_button_ok), 
					new DialogInterface.OnClickListener() {

				//                                @Override
				public void onClick(DialogInterface dialog, int which) {
					// 아래의 모든 activity 를 닫는 종료 코드가 작동하지 않는다??
					ActivityManager am = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
					am.restartPackage(getPackageName());

					// 다시 예전 방식으로 사용.
					System.exit(0);
				}
			}).show();

			break;

		default:
			break;
		}

		return super.onCreateDialog(id);
		
	}

	/* (non-Javadoc)
	 * @see android.app.Activity#onPause()
	 */
//	@Override
//	protected void onPause() {
//		// TODO Auto-generated method stub
//		super.onPause();
//		
//		getPreferenceScreen().getSharedPreferences().unregisterOnSharedPreferenceChangeListener(this);
//	}

	/* (non-Javadoc)
	 * @see android.app.Activity#onResume()
	 */
	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		
		getPreferenceScreen().getSharedPreferences().registerOnSharedPreferenceChangeListener(this);
	}
	
	/* 뒤로 가기 버튼을 정의 한다.
	 * 
	 * @see android.app.Activity#onBackPressed()
	 */
	@Override
	public void onBackPressed() {
		// TODO Auto-generated method stub
		showDialog(ALERT_DIALOG_EXIT_ID);
//		super.onBackPressed();
	}
	
	/* 최상위 프로세스가 아닐 경우 프로세스를 종료 한다.
	 * 
	 * => Home Key 를 눌렀을때 프로세스를 종료 한다.
	 * 
	 * @see android.app.Activity#onPause()
	 */
	@Override
	protected void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
		
		getPreferenceScreen().getSharedPreferences().unregisterOnSharedPreferenceChangeListener(this);
		
		if(!isForegrdound()) {
			System.exit(0);
		}
	}
	
	/**
	 * 현재 프로세스가 최상위로 실행중인지 검사 한다.
	 * 
	 * true : 최상위
	 * 
	 * @return
	 */
	public boolean isForegrdound() {
	    ActivityManager am = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
	    List<RunningTaskInfo> list = am.getRunningTasks(1);
	    ComponentName cn = list.get(0).topActivity;
	    String name = cn.getPackageName();
	     
	    return name.indexOf(getPackageName()) > -1;
	}
}
